package com.rpc.core.loadbalance.impl;

import com.rpc.core.holder.rag.RegInfoEnhancer;
import com.rpc.core.loadbalance.LoadBalance;
import com.rpc.core.remoting.Client;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

public class RandomLoadBalance implements LoadBalance {
    @Override
    public RegInfoEnhancer get(List<RegInfoEnhancer> list) {

        ArrayList<RegInfoEnhancer> enhancers = new ArrayList<>(list);
        HashSet<RegInfoEnhancer> useFailSet = new HashSet<>();

        for (; ; ) {
            int index = new Random().nextInt(list.size());
            RegInfoEnhancer enhancer = enhancers.get(index);

            if (useFailSet.contains(enhancer)) {
                continue;
            }
            Client client = enhancer.getClient();
            if (client != null) {
                return enhancer;
            } else {
                if (enhancers.size() == useFailSet.size()) {
                    return null;
                }
                useFailSet.add(enhancer);
            }

        }

    }
}
